package com.lebang.medicalInquiry.initializer;


import com.lebang.medicalInquiry.handler.LiveMessageHandler;
import com.lebang.medicalInquiry.handler.MessageHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @version V1.0
 * @author: zpc
 * @date:
 */
@Component
public class ServerLiveInitializer extends ChannelInitializer<SocketChannel> {

    @Autowired
    private LiveMessageHandler messageHandler;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {

        ChannelPipeline pipeline = ch.pipeline();
//                            pipeline.addLast(new StringEncoder());
//                            pipeline.addLast("decoder", new StringDecoder());
//        pipeline.addLast(new IpDecode());
        pipeline.addLast(new HttpServerCodec());
        //以块的方式来写的处理器
        pipeline.addLast(new ChunkedWriteHandler());
        pipeline.addLast(new HttpObjectAggregator(1024 * 10));
        //IdleStateHandler(空闲心跳检测) netty会检测 客户端 的读写是否超时  如果超出指定时间 就断开连接(超出指定时间后的操作需要自己实现一个双向通信处理器ChannelDuplexHandler 重写 userEventTriggered方法)
//        pipeline.addLast(new IdleStateHandler(30, 20, 0));
//        pipeline.addLast(new ReadTimeoutHandler(30, TimeUnit.SECONDS));
//   WebSocketServerProtocolHandler 是处理websoket的握手请求, websoketPath 是代表要把那个路径请求变成websoket  checkStartsWith 代表 使用开头匹配 还是 相等的模式匹配

        pipeline.addLast(new WebSocketServerProtocolHandler("/ws", null, false));
        pipeline.addLast(messageHandler);
    }
}
